package com.hzqy.web.ac;

import com.hzqy.commons.utils.*;
import com.hzqy.service.picture.PictureServiceBean;
import com.hzqy.service.pms.PmsServiceBean;
import com.hzqy.service.zxbh.ZxbhUserService;
import com.hzqy.web.vo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hzqy.commons.utils.FileUtil.fileCheck;

@Controller
@RequestMapping("/zxbh")
public class ZxbhUserAction {

	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	private static final String[] allowedFileType = new String[]{"png", "jpg", "gif","zip","jar","tar","docx","doc","xlsx","xls","flv","mp4","mp3","mpg","avi","mov","wmv"};
	@Autowired
	private ZxbhUserService zxbhUserService;
	
	@Resource
	private PmsServiceBean pmsServiceBean;

	@Resource
	private PictureServiceBean pictureServiceBean;
	
	@RequestMapping("/add_user_credit")
	@ResponseBody
	public Object addUserCredit(UserCreditVo userCreditVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.addUserCredit(userCreditVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","新增失败!flag="+flag);
		}
		return resultMap;
	}

	@RequestMapping("/select_user_credit_list")
	@ResponseBody
	public Object selectUserCreditList(HttpSession session, UserCreditVo userCreditVo, int page, int rows) {
		PmsUserVo userVo = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		//父级组织id为0是根组织,有最高权限 否则必须使用组织本身id覆盖companyid,就看不到别的组织的内容了 
		if(userVo.getParentOrgId() > 0){
			String orgIds = pmsServiceBean.getAuthorityPmsOrgIds(userVo);
			userCreditVo.setF_po_ids(orgIds);
		}
		Map<String,Object> userListMap = zxbhUserService.selectUserCreditList(userCreditVo,page,rows);
		return userListMap;
	}
	
	@RequestMapping("/select_user_account_list")
	@ResponseBody
	public Object selectUserAccountList(HttpSession session, UserAccountVo userAccountVo, int page, int rows) {
		PmsUserVo userVo = (PmsUserVo) session.getAttribute(ConstantUtils.SESSION_USER);
		//父级组织id为0是根组织,有最高权限 否则必须使用组织本身id覆盖companyid,就看不到别的组织的内容了 
		if(userVo.getParentOrgId() > 0){
			String orgIds = pmsServiceBean.getAuthorityPmsOrgIds(userVo);
			if(userAccountVo.getF_po_ids()==null||"".equals(userAccountVo.getF_po_ids())||userAccountVo.getF_po_ids().equals(orgIds)){
				userAccountVo.setF_po_ids(orgIds);
			}else{
				boolean flag=true;
				String[] orgIdlist=orgIds.split(",");
				for(int i=0;i<orgIdlist.length;i++){
					if(userAccountVo.getF_po_ids().equals(orgIdlist[i])){
						flag=false;
						break;
					}
				}
				if(flag){//该企业不在列表内则不可查询
					userAccountVo.setF_po_ids(orgIds);
				}
			}
		}
		Map<String,Object> userListMap = zxbhUserService.selectUserAccountList(userAccountVo,page,rows);
		return userListMap;
	}
	
	@RequestMapping("/add_user_account")
	@ResponseBody
	public Object addUserAccount(UserAccountVo userAccountVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.addUserAccount(userAccountVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增成功!");
		} else if(flag==-2){
			resultMap.put("success", false);
			resultMap.put("result","新增失败!重复的sn码："+userAccountVo.getF_uaz_sn());
		} else{
			resultMap.put("success", false);
			resultMap.put("result","新增失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/delete_user_account")
	@ResponseBody
	public Object deleteUserAccount(int f_uaz_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.deleteUserAccount(f_uaz_id);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/update_user_account")
	@ResponseBody
	public Object updateUserAccount(UserAccountVo userAccountVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.updateUserAccount(userAccountVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else if(flag==-2){
			resultMap.put("success", false);
			resultMap.put("result","新增失败!重复的sn码："+userAccountVo.getF_uaz_sn());
		}  else {
			resultMap.put("success", false);
			resultMap.put("result","修改失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/select_user_account")
	@ResponseBody
	public Object selectUserAccount(int f_uaz_id) {
		UserAccountVo userAccountVo = zxbhUserService.selectUserAccount(f_uaz_id);
		return userAccountVo;
	}
	
	@RequestMapping("/select_user_account_wchat_list")
	@ResponseBody
	public Object selectUserAccountWchatList(HttpSession session, UserAccountZxbhWchatVo userAccountZxbhWchatVo, int page, int rows) {
		Map<String,Object> userListMap = zxbhUserService.selectUserAccountWchatList(userAccountZxbhWchatVo,page,rows);
		return userListMap;
	}
	
	@RequestMapping("/add_user_account_wchat")
	@ResponseBody
	public Object addUserAccountWchat(UserAccountZxbhWchatVo userAccountZxbhWchatVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.addUserAccountWchat(userAccountZxbhWchatVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","新增失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/delete_user_account_wchat")
	@ResponseBody
	public Object deleteUserAccountWchat(int f_uazw_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.deleteUserAccountWchat(f_uazw_id);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/update_user_account_wchat")
	@ResponseBody
	public Object updateUserAccountWchat(UserAccountZxbhWchatVo userAccountZxbhWchatVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.updateUserAccountWchat(userAccountZxbhWchatVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改失败!flag="+flag);
		}
		return resultMap;
	}
	
	@RequestMapping("/select_user_account_wchat")
	@ResponseBody
	public Object selectUserAccountWchat(int f_uazw_id) {
		UserAccountZxbhWchatVo userAccountZxbhWchatVo = zxbhUserService.selectUserAccountWchat(f_uazw_id);
		return userAccountZxbhWchatVo;
	}
	
	@RequestMapping("/clearUserBySn")
	@ResponseBody
	public Object clearUserBySn(String sn) {
		Map<String, Object> resultMap = zxbhUserService.clearUserBySn(sn);
		return resultMap;
	}
	
	@RequestMapping("/clearWebCache")
	@ResponseBody
	public Object clearWebCache() {
		Map<String, Object> resultMap = zxbhUserService.clearWebCache();
		return resultMap;
	}
	
	@RequestMapping("/batch_add_user_account")
	@ResponseBody
	public Object batchAddUserAccount(@RequestParam(value = "uploadify") MultipartFile file ,int f_cc_companyid) throws Exception {
		int successCount = 0;
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		StringBuffer str = new StringBuffer();
		StringBuffer str2 = new StringBuffer();
		InputStream is = null;
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();

			if (FileType.checkFileType(file.getInputStream(), allowedFileType)) {
			LOG.debug("批量导入智学宝盒用户开始");
			is = file.getInputStream();
			List<Map<String, Object>> list = ExcelUtil.parseExcel(is, ExcelUtil.ALLOWED_EMPTY_MODE, null);
			LOG.debug("解析excel完成, 开始循环入库智学宝盒用户");
			String f_uaz_member_enddate = "2030-12-20 23:59:59";
			String f_uaz_member_startdate = format.format(new Date());
			int totalCount = 0;
			for (int i = 0; i < list.size(); i++) {
				try {
					Map<String, Object> m = list.get(i);
					UserAccountVo userAccountVo = ConvertBeanUtil.getBeanFromMap(m, UserAccountVo.class, UserAccountVo.class.getName());
					if (StringUtils.isEmpty(userAccountVo.getF_uaz_sn()) && StringUtils.isEmpty(userAccountVo.getF_uaz_realName())) {
						continue;
					}

					totalCount++;

					if (StringUtils.isEmpty(userAccountVo.getF_uaz_sn())) {
						str.append("第").append(totalCount).append("条sn为空! ").append("<br/>");
						continue;
					}

					if (StringUtils.isEmpty(userAccountVo.getF_uaz_realName())) {
						str.append("第").append(totalCount).append("条姓名为空! ").append("<br/>");
						continue;
					}

					String phones = userAccountVo.getPhones();
					int flag = 0;
					userAccountVo.setF_uaz_orgId(f_cc_companyid);
					userAccountVo.setF_uaz_status(1);
					userAccountVo.setF_uaz_product_give(2);
					userAccountVo.setF_uaz_give_strategy(1);
					userAccountVo.setF_uaz_member_startdate(f_uaz_member_startdate);
					userAccountVo.setF_uaz_member_enddate(f_uaz_member_enddate);
					flag = zxbhUserService.addUserAccount(userAccountVo);
					if (flag == -2) {//sn码重复
						str.append("第").append(totalCount).append("条sn码重复!重复的sn码为： " + userAccountVo.getF_uaz_sn()).append("<br/>");
					} else {
						int f_uaz_id = userAccountVo.getF_uaz_id();
						if (phones != null && !"".equals(phones.trim())) {
							if (phones.indexOf("，") > -1) {
								String phoneArr[] = phones.split("，");
								UserAccountZxbhWchatVo userAccountZxbhWchatVo = new UserAccountZxbhWchatVo();
								userAccountZxbhWchatVo.setF_uazw_userId(f_uaz_id);
								userAccountZxbhWchatVo.setF_uazw_sn(userAccountVo.getF_uaz_sn());
								userAccountZxbhWchatVo.setF_uazw_status(1);
								userAccountZxbhWchatVo.setF_uazw_userType(1);
								for (int j = 0; j < phoneArr.length; j++) {
									userAccountZxbhWchatVo.setF_uazw_phone(phoneArr[j]);
									zxbhUserService.addUserAccountWchat(userAccountZxbhWchatVo);
								}
							} else {
								UserAccountZxbhWchatVo userAccountZxbhWchatVo = new UserAccountZxbhWchatVo();
								userAccountZxbhWchatVo.setF_uazw_userId(f_uaz_id);
								userAccountZxbhWchatVo.setF_uazw_sn(userAccountVo.getF_uaz_sn());
								userAccountZxbhWchatVo.setF_uazw_phone(phones);
								userAccountZxbhWchatVo.setF_uazw_status(1);
								userAccountZxbhWchatVo.setF_uazw_userType(1);
								zxbhUserService.addUserAccountWchat(userAccountZxbhWchatVo);
							}
						}
					}

					successCount += (flag > 0 ? 1 : 0);
					if (flag <= 0 && userAccountVo.getF_uaz_realName() != null) {
						str2.append(i + 1).append(",");
					}
				} catch (Exception e) {
					LOG.error("", e);
					//str.append("第").append(i+1).append("条 出错! ").append(e.getMessage()).append("<br/>");
				}
				LOG.debug("批量完成");
				if (str2.length() > 0) {
					str.append("第").append(str2.substring(0, str2.length() - 1)).append("条导入失败! ").append("<br/>");
				}
			}
			str.append("批量导入完成， 一共：").append(totalCount).append("条数据, 成功").append(successCount).append(", 失败").append(totalCount - successCount);
		}
			} catch (Exception e) {
				LOG.error("", e);
				//str.append("批量导入失败: " + e.getMessage());
			} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
			return str.toString();
		}

	@RequestMapping("/select_apk_upgrade_list")
	@ResponseBody
	public Object selectApkUpgradeList(HttpSession session, ApkUpgradeVo apkUpgradeVo, int page, int rows) {
		Map<String,Object> apkUpgradeListMap = zxbhUserService.selectApkUpgradeList(apkUpgradeVo,page,rows);
		return apkUpgradeListMap;
	}

	@RequestMapping("/add_apk_upgrade")
	@ResponseBody
	public Object addApkUpgrade(ApkUpgradeVo apkUpgradeVo) {
		Map<String,Object> resultMap = zxbhUserService.addApkUpgrade(apkUpgradeVo);
		return resultMap;
	}

	@RequestMapping("/update_apk_upgrade")
	@ResponseBody
	public Object updateApkUpgrade(ApkUpgradeVo apkUpgradeVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.updateApkUpgrade(apkUpgradeVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改失败!flag="+flag);
		}
		return resultMap;
	}

/*	@RequestMapping("/uploadApk")
	@ResponseBody
	public Object uploadPicture(HttpServletRequest request , HttpServletResponse response, HttpSession session) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String result = null;
		int flag = -1;
		String picLeftFile = SystemConfigUtils.getSysConfig("apk_save_path");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("uploadify");
		String uploadifyFileName = file.getOriginalFilename();
		if (FileType.checkFileType(file.getInputStream(), allowedFileType)) {
			String fileName = pictureServiceBean.getFileName(uploadifyFileName);
			LOG.debug("apk_path：" + picLeftFile + fileName);
			if(fileCheck(picLeftFile, fileName)){
				File picFile = new File(picLeftFile, fileName);
				if (!picFile.exists())
					picFile.mkdirs();
				try {
					file.transferTo(picFile);
				} catch (Exception e) {
					LOG.error("上传apk异常：", e);
				}
				result = fileName;
				flag = 1;
				resultMap.put("result", result);
				resultMap.put("flag", flag);
			}
			return resultMap;
		} else {
			return resultMap;
		}
	}*/

	@RequestMapping("/select_zlxUrl_list")
	@ResponseBody
	public Object selectZlxUrlList(HttpSession session, StatZxbhConfUrlVo statZxbhConfUrlVo, int page, int rows) {
		Map<String,Object> userListMap = zxbhUserService.selectZlxUrlList(statZxbhConfUrlVo,page,rows);
		return userListMap;
	}

	@RequestMapping("/select_zlxUrl")
	@ResponseBody
	public Object selectzlxUrl(int f_szcu_id) {
		StatZxbhConfUrlVo statZxbhConfUrlVo = zxbhUserService.selectzlxUrl(f_szcu_id);
		return statZxbhConfUrlVo;
	}

	@RequestMapping("/add_zlxUrl")
	@ResponseBody
	public Object addZlxUrl(StatZxbhConfUrlVo statZxbhConfUrlVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.addZlxUrl(statZxbhConfUrlVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","新增成功!");
		} else{
			resultMap.put("success", false);
			resultMap.put("result","新增失败!flag="+flag);
		}
		return resultMap;
	}

	@RequestMapping("/delete_zlxUrl")
	@ResponseBody
	public Object deleteZlxUrl(int f_szcu_id) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.deleteZlxUrl(f_szcu_id);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","删除成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","删除失败!flag="+flag);
		}
		return resultMap;
	}

	@RequestMapping("/update_zlxUrl")
	@ResponseBody
	public Object updateZlxUrl(StatZxbhConfUrlVo statZxbhConfUrlVo) {
		Map<String,Object> resultMap = new HashMap<String,Object>();
		int flag = zxbhUserService.updateZlxUrl(statZxbhConfUrlVo);
		if(flag>0) {
			resultMap.put("success", true);
			resultMap.put("result","修改成功!");
		} else {
			resultMap.put("success", false);
			resultMap.put("result","修改失败!flag="+flag);
		}
		return resultMap;
	}
}
